import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { RedisService } from '../utils/redis.service';

@Injectable()
export class AuthService {
  private readonly redisPrefix = 'auth:jwt:';
  private readonly tokenTTL = 60 * 60 * 24;

  constructor(
    private readonly jwtService: JwtService,
    private readonly redisService: RedisService,
  ) {}

  async generateToken(payload: any): Promise<string> {
    const token = this.jwtService.sign(payload, { expiresIn: this.tokenTTL });
    await this.redisService.set(this.redisPrefix + token, JSON.stringify(payload), this.tokenTTL);
    return token;
  }

  async validateToken(token: string): Promise<any> {
    const cached = await this.redisService.get(this.redisPrefix + token);
    if (!cached) throw new UnauthorizedException('Token 已过期或无效');
    try {
      return this.jwtService.verify(token);
    } catch {
      throw new UnauthorizedException('Token 验证失败');
    }
  }

  async revokeToken(token: string) {
    await this.redisService.del(this.redisPrefix + token);
  }
}
